package com.example.recyclerviewtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
    private static final String TAG = "FruitAdapter";

    private final ArrayList<Fruit> mFruits;

    FruitAdapter(ArrayList<Fruit> fruits) {
        this.mFruits = fruits;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivFruit;
        TextView tvName;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivFruit = itemView.findViewById(R.id.iv_fruit);
            tvName = itemView.findViewById(R.id.tv_name);
        }
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        final ViewHolder viewHolder = new ViewHolder(view);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (parent instanceof RecyclerView) {
                    int position = ((RecyclerView) parent).getChildAdapterPosition(view);
                    onRecyclerItemClickListener.onRecyclerItemClick(position);
                }
            }
        });

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit fruit = mFruits.get(position);
        holder.ivFruit.setImageResource(fruit.getImageId());
        holder.tvName.setText(fruit.getName());
    }



    private OnRecyclerItemClickListener onRecyclerItemClickListener;

    interface  OnRecyclerItemClickListener {
        void onRecyclerItemClick(int position);
    }
    @Override
    public int getItemCount() {
        return mFruits.size();
    }

    void setOnRecyclerItemClickListener(OnRecyclerItemClickListener onRecyclerItemClickListener) {
        this.onRecyclerItemClickListener = onRecyclerItemClickListener;
    }

}
